package com.sgb.capital.view.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StyleSpan;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.sgb.capital.R;
import com.sgb.capital.base.BaseActivity;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.OnZTabSelectedListener;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.CapitalBusinessmanagementActivityBinding;
import com.sgb.capital.model.Bean;
import com.sgb.capital.model.PayOrderBean;
import com.sgb.capital.model.PayOrderEntity;
import com.sgb.capital.model.SelBean;
import com.sgb.capital.utils.AdapterOnItemClick;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.view.pop.SelectPop;
import com.sgb.capital.view.pop.ZSelectPop;
import com.sgb.capital.view.ui.adapter.FinanceFlowItemAdapter;
import com.sgb.capital.view.ui.adapter.OrderPayAdapter;
import com.sgb.capital.view.widget.xrecyclerview.ZXRecyclerView;
import com.sgb.capital.viewmodel.PayOrderModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

/**
 * 作者:张磊
 * 日期:2021/9/2 0002
 * 说明:业务管理
 */
public class BusinessManagementActivity extends BaseActivity {

    private CapitalBusinessmanagementActivityBinding mBinding;
    private OrderPayAdapter mAdapter;
    private PayOrderBean mOrderBean = new PayOrderBean();
    private List<Bean> mTimeBeans = new ArrayList<>();
    private SelectPop mSelectPop;
    private String mStr = "商品";
    PayOrderModel mModel;
    private String mTime;
    private ZSelectPop mZSelectPop;
    private FinanceFlowItemAdapter mFlowItemAdapter;
    private List<Bean> mType;
    private List<Bean> mTimes;
    private TextView mTextView;
    private ImageView mImg;
    private String mStrkey = "1";
    private List<SelBean> mChildren;
    private int mCode;

    public static void start(Context context, int code) {
        Intent intent = new Intent(context, BusinessManagementActivity.class);
        intent.putExtra("code", code);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }


    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        mBinding = DataBindingUtil.setContentView(this, R.layout.capital_businessmanagement_activity);
        mSelectPop = new SelectPop(this);
        mZSelectPop = new ZSelectPop(this);

        mSelectPop.setBgView(mBinding.grayLayout);
        mZSelectPop.setBgView(mBinding.grayLayout);
        mBinding.rvList.setLayoutManager(new GridLayoutManager(Utils.getContext(), 1));
        mAdapter = new OrderPayAdapter(this, null, null);
        mBinding.rvList.setAdapter(mAdapter);
        mModel = new ViewModelProvider(this).get(PayOrderModel.class);


        // 选项
        mBinding.rvItem.setLayoutManager(new GridLayoutManager(Utils.getContext(), 2));
        mFlowItemAdapter = new FinanceFlowItemAdapter(null);
        mBinding.rvItem.setAdapter(mFlowItemAdapter);

    }

    public void initData() {
        mCode = getIntent().getIntExtra("code", 1);
        mBinding.tvTitle.setText(mCode == 1 ? "待付账单" : mCode == 2 ? "已付账单" : mCode == 3 ? "应收账单" : "已收账单");
        mBinding.tvType.setText(mCode == 1 ? "待支付-商品材料" : mCode == 5 ? "已支付-商品材料" : mCode == 6 ? "应收-商品材料" : "已收-商品材料");
        mBinding.tvRight.setVisibility(mCode==1?View.VISIBLE:View.GONE);
        mAdapter.mType = mCode;
        mStrkey = mCode+"";
        Utils.setBeans(mTimeBeans, new String[]{"全部", "今日", "最近一周", "最近一个月", "最近三个月", "最近半年", "最近一年"});
        mBinding.tvName.setText((mCode == 1 || mCode == 5) ? "创建时间" : "付款时间");
        mType = Utils.setDatas(new String[]{"全部", "审批中", "已通过", "已拒绝"});
        mTimes = Utils.setDatas(new String[]{"全部", "今日", "最近一周", "最近一个月", "最近三个月", "最近半年", "最近一年"});
        List<Bean> beans = new ArrayList<>();
        beans.add(new Bean((mCode == 1 || mCode == 3) ? "创建时间" : "付款时间"));
        System.out.println("名字=="+ beans.get(0).name);
        if (mCode ==1){
            beans.add(new Bean("审批状态"));
        }
        mFlowItemAdapter.setNewInstance(beans);
        mModel.getSelectTree(this);
    }

    public void initListener() {
        mBinding.tab.addOnTabSelectedListener(new OnZTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab == null || tab.getText() == null) {
                    return;
                }
                String trim = tab.getText().toString().trim();
                SpannableString spannableString = new SpannableString(trim);
                StyleSpan styleSpan = new StyleSpan(Typeface.BOLD);
                spannableString.setSpan(styleSpan, 0, trim.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                tab.setText(spannableString);
                System.out.println("key==" + mChildren.get(tab.getPosition()).strKey);
                mStr = mChildren.get(tab.getPosition()).name;
                mOrderBean.page = 1;
                int type = mCode;
                if (mChildren.get(tab.getPosition()).name.contains("在线转账") && type == 2) {
                    mAdapter.mType = 5;
                } else if (mChildren.get(tab.getPosition()).name.contains("在线转账")) {
                    mAdapter.mType = 6;
                } else {
                    mAdapter.mType = type;
                }
                mOrderBean.orderType = mChildren.get(tab.getPosition()).strKey;
                sRefresh();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab == null || tab.getText() == null) {
                    return;
                }
                String trim = tab.getText().toString().trim();
                SpannableString spannableString = new SpannableString(trim);
                StyleSpan styleSpan = new StyleSpan(Typeface.NORMAL);
                spannableString.setSpan(styleSpan, 0, trim.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                tab.setText(spannableString);
            }
        });

        mFlowItemAdapter.setOnItemClickListener((adapter, view, position) -> {
            LinearLayout linearLayout = (LinearLayout) view;
            mTextView = (TextView) linearLayout.getChildAt(0);
            mImg = (ImageView) linearLayout.getChildAt(1);
            if (mTextView.getText().toString().contains("时间") || mTextView.getText().toString().contains("审批状态")) {
                mTextView.setTextColor(Utils.getColor(R.color.color_333333));
            }
            mImg.setRotation(180);
            switch (position) {
                case 0:
                    mSelectPop.mType = 1;
                    mSelectPop.setData(mTimes);
                    mSelectPop.mAdapter.setDefItem(mSelectPop.mPos1);
                    break;
                case 1:
                    mSelectPop.mType = 2;
                    mSelectPop.setData(mType);
                    mSelectPop.mAdapter.setDefItem(mSelectPop.mPos2);
                    break;
            }
            mSelectPop.showPopwindow(mBinding.view, 0, 0);
        });

        mBinding.rvList.setLoadingListener(new ZXRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mOrderBean.page = 1;
                sRefresh();
            }

            @Override
            public void onLoadMore() {
                mOrderBean.page++;
                sRefresh();
            }
        });

        mBinding.tvRight.setOnClickListener(v -> startActivity(new Intent(this, OrderErrorActivity.class)));
        mAdapter.setOnItemClick(new AdapterOnItemClick<PayOrderEntity>() {
            @Override
            public void onItemClick(PayOrderEntity payOrderEntity, int position) {
                BillOrderDetailsActivity.start(BusinessManagementActivity.this, mAdapter.mType, payOrderEntity.orderId, payOrderEntity.id, mStr);
            }
        });
        mZSelectPop.setOnDismissListener(() -> {
            mBinding.ivArrow.setRotation(0);
            if (mZSelectPop.mIsClick) {
                mOrderBean.page = 1;
                mOrderBean.orderType = mZSelectPop.strKey;
                if (mZSelectPop.name.contains("待付账单")) {
                    mAdapter.mType = 1;
                    mModel.getToBePayOrderList(this, mOrderBean);
                    mBinding.tvType.setText("待支付" + "-" + mZSelectPop.name.split("-")[1]);
                } else if (mZSelectPop.name.contains("已付账单")) {
                    mBinding.tvType.setText("已支付" + "-" + mZSelectPop.name.split("-")[1]);
                    mAdapter.mType = mZSelectPop.name.split("-")[1].contains("转账") ? 5 : 2;
                    if (mAdapter.mType == 2) {
                        mModel.getPay2OrderList(this, mOrderBean);
                    } else {
                        mModel.getTransferInfoList(this, mOrderBean);
                    }
                } else if (mZSelectPop.name.contains("应收账单")) {
                    mAdapter.mType = 3;
                    mModel.getReceivableOrderList(this, mOrderBean);
                    mBinding.tvType.setText("应收" + "-" + mZSelectPop.name.split("-")[1]);
                } else {
                    mBinding.tvType.setText("已收" + "-" + mZSelectPop.name.split("-")[1]);
                    mAdapter.mType = mZSelectPop.name.split("-")[1].contains("转账") ? 6 : 4;
                    if (mAdapter.mType == 4) {
                        mModel.getReceivedOrderList(this, mOrderBean);
                    } else {
                        mModel.getReceivedTransferOrderList(this, mOrderBean);
                    }
                }
                mBinding.tvName.setText(mSelectPop.mPos1 == 0 ?
                        (mAdapter.mType == 1 || mAdapter.mType == 3) ? "创建时间" : "付款时间" : mSelectPop.mBean.name);
                String s = mZSelectPop.name.split("-")[1];
                if (mAdapter.mType > 4) {
                    mStr = "转账";
                } else {
                    mStr = s.contains("商品") ? "商品" : s;
                }
                mFlowItemAdapter.mLlSelect.setVisibility(mAdapter.mType != 1 ? View.INVISIBLE : View.VISIBLE);
            }
        });
        mBinding.rlSelect.setOnClickListener(v -> {
            if (mZSelectPop.mDatas.size() == 0) {
                mModel.getSelectTree(this);
                return;
            }
            Utils.hide(this);
            mBinding.ivArrow.setRotation(180);
            mZSelectPop.showPopwindow(mBinding.view2, 0, 0);
        });


        mSelectPop.setOnDismissListener(() -> {
            if (mSelectPop.mIsClick) {
                if (mSelectPop.mType == 1) {
                    mTextView.setText(mSelectPop.mPos1 == 0 ? (mAdapter.mType == 1 || mAdapter.mType == 3) ? "创建时间" : "付款时间" : mSelectPop.mBean.name);
                    mOrderBean.startTime = null;
                    mOrderBean.endTime = null;
                } else if (mSelectPop.mType == 2) {
                    mTextView.setText(mSelectPop.mPos2 == 0 ? "审批状态" : mSelectPop.mBean.name);
                    mOrderBean.payApplyState = null;
                }
                if (mSelectPop.mType == 1 && mSelectPop.mPos1 != 0) {
                    mTime = mSelectPop.mBean.name.contains("今日") ? Utils.getStartAndEndTime(0, 0, "今日")
                            : mSelectPop.mBean.name.contains("最近一周") ? Utils.getStartAndEndTime(1, 7, "最近一周")
                            : mSelectPop.mBean.name.contains("最近一个月") ? Utils.getStartAndEndTime(2, 1, "最近一个月")
                            : mSelectPop.mBean.name.contains("最近三个月") ? Utils.getStartAndEndTime(2, 3, "最近三个月")
                            : mSelectPop.mBean.name.contains("最近半年") ? Utils.getStartAndEndTime(2, 6, "最近六个月")
                            : Utils.getStartAndEndTime(3, 1, "最近一年");
                    mOrderBean.startTime = mTime.split("-")[0];
                    mOrderBean.endTime = mTime.split("-")[1];
                } else if (mSelectPop.mType == 2 && mSelectPop.mPos2 != 0) {
                    mOrderBean.payApplyState = mSelectPop.mPos2 + "";
                }
                mTextView.setTextColor(Utils.getColor(mSelectPop.mType == 1 ?
                        mSelectPop.mPos1 != 0 ? R.color.color_EF4033 : R.color.color_666666 :
                        mSelectPop.mType == 2 ? mSelectPop.mPos2 != 0 ? R.color.color_EF4033 : R.color.color_666666 :
                                mSelectPop.mPos3 != 0 ? R.color.color_EF4033 : R.color.color_666666
                ));
                mImg.setImageResource(mSelectPop.mType == 1 ? mSelectPop.mPos1 != 0 ?
                        R.mipmap.down : R.mipmap.ic_down_arrow_n : mSelectPop.mType == 2 ?
                        mSelectPop.mPos2 != 0 ? R.mipmap.down : R.mipmap.ic_down_arrow_n :
                        mSelectPop.mPos3 != 0 ? R.mipmap.down : R.mipmap.ic_down_arrow_n
                );
                mOrderBean.page = 1;
                if (mAdapter.mType == 1) {
                    mModel.getToBePayOrderList(this, mOrderBean);
                } else if (mAdapter.mType == 2) {
                    mModel.getPay2OrderList(this, mOrderBean);
                } else if (mAdapter.mType == 3) {
                    mModel.getReceivableOrderList(this, mOrderBean);
                } else if (mAdapter.mType == 4) {
                    mModel.getReceivedOrderList(this, mOrderBean);
                } else if (mAdapter.mType == 5) {
                    mModel.getTransferInfoList(this, mOrderBean);
                } else {
                    mModel.getReceivedTransferOrderList(this, mOrderBean);
                }
            }
            mImg.setRotation(0);
            mSelectPop.mIsClick = false;
        });

        mBinding.llView.setOnClickListener(v -> {
            mBinding.ivImage.setRotation(180);
            mSelectPop.setData(mTimeBeans);
            mSelectPop.showPopwindow(mBinding.view, 0, 0);
        });
        mBinding.ivBack.setOnClickListener(v -> finish());
        mBinding.etSs.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                mOrderBean.page = 1;
                sRefresh();
            }
            return false;
        });
    }

    private void sRefresh() {
        String trim = mBinding.etSs.getText().toString().trim();
        try {
            Long.parseLong(trim);
            mOrderBean.orderId = mBinding.etSs.getText().toString().trim();
            refresh();
        } catch (Exception e) {
            mOrderBean.payeeName = mBinding.etSs.getText().toString().trim();
            refresh();
        }
    }

    private void refresh() {
        if (mAdapter.mType == 1) {
            mModel.getToBePayOrderList(BusinessManagementActivity.this, mOrderBean);
        } else if (mAdapter.mType == 2) {
            mModel.getPay2OrderList(BusinessManagementActivity.this, mOrderBean);
        } else if (mAdapter.mType == 3) {
            mModel.getReceivableOrderList(BusinessManagementActivity.this, mOrderBean);
        } else if (mAdapter.mType == 4) {
            mModel.getReceivedOrderList(BusinessManagementActivity.this, mOrderBean);
        } else if (mAdapter.mType == 5) {
            mModel.getTransferInfoList(BusinessManagementActivity.this, mOrderBean);
        } else {
            mModel.getReceivedTransferOrderList(BusinessManagementActivity.this, mOrderBean);
        }
    }

    @Override
    public void initObserve() {
        mModel.mPayOrderList.observe(this, payOrderEntities -> {
            if (mOrderBean.page != 1) {
                mBinding.rvList.loadMoreComplete();
                if (payOrderEntities.size() != 0) {
                    mAdapter.addDatas(payOrderEntities);
                } else {
                    mBinding.rvList.setNoMore(true);
                }
            } else {
                mBinding.errorView.setVisibility(payOrderEntities.size() != 0 ? View.GONE : View.VISIBLE);
                mBinding.rvList.refreshComplete();
                mBinding.rvList.setLoadingMoreEnabled(true);
                mBinding.rvList.scrollToPosition(0);
                mAdapter.setDatas(payOrderEntities);
                mAdapter.notifyDataSetChanged();
            }
        });
        mModel.mSelBean.observe(this, selBeans -> {
            // TODO: 2022/1/13 0013
            // TODO: 2022/1/13 0013
            // TODO: 2022/1/13 0013

            for (SelBean selBean : selBeans) {
                if (mStrkey.equals("1")) {
                    setItem(selBean, "1");
                } else if (mStrkey.equals("2")) {
                    setItem(selBean, "2");
                } else if (mStrkey.equals("3")) {
                    setItem(selBean, "3");
                } else if (mStrkey.equals("4")) {
                    setItem(selBean, "4");
                }
            }
         /*   mZSelectPop.setData(selBeans, false);
            mZSelectPop.showPopwindow(mBinding.view2, 0, 0);*/
        });

    }

    private void setItem(SelBean selBean, String s) {
        if (selBean.strKey.equals(s)) {
            mChildren = selBean.children;
            for (SelBean item : selBean.children) {
                mBinding.tab.addTab(mBinding.tab.newTab().setText(item.name));
            }
            mBinding.tab.getTabAt(0).select();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Subscribe
    public void getCode(ZMessageEvent event) {
        switch (event.code) {
            case Constants.EVENT_HIDE_ORDERID:
                boolean isShow = (boolean) event.data;
                if (isShow) {
                    test();
                } else {
                    Utils.postDelay(() -> sRefresh(), 500);
                }
                break;
            case Constants.EVENT_REFRESH:
                Utils.postDelay(() -> sRefresh(), 500);
                break;
        }
    }

    private void test() {
        mBinding.tvTitle.setText("已付账单");
        mBinding.tvType.setText("已支付" + "-" + (mStr.contains("转账") ? "在线转债" : mStr));
        mAdapter.mType = 2;
        mZSelectPop.mlastIndex1 = 1;
        mOrderBean.page = 1;
        mZSelectPop.mlastIndex2 = mStr.contains("商品") ? 0 :
                mStr.contains("物流") ? 1 :
                        mStr.contains("租赁") ? 2 :
                                mStr.contains("企业服务") ? 4 :
                                        mStr.contains("食住行") ? 3 : 5;
        mZSelectPop.setNewInstance();
        Utils.postDelay(() -> sRefresh(), 500);
    }
}